import { PrismaService } from '@app/prisma';
import { CollegeEntity } from '@app/prisma/college.entity/college.entity';
import { CollegePagination } from '@app/prisma/pagination/college.pagination';
import { ForbiddenError } from '@nestjs/apollo';
import { UseGuards } from '@nestjs/common';
import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql';
import { GqlAuthGuard, GqlAuthPowerGuard, AccountPower } from 'src/auth/auth.guard';

@Resolver()
export class CollegeResolver {
    constructor(
        private readonly prisma: PrismaService
    ) { }

    @Query(() => CollegePagination)
    @UseGuards(GqlAuthGuard)
    async getCollege() {

    }

    @Query(() => [CollegeEntity])
    getAllCollege() {
        return this.prisma.college.findMany({
            orderBy: {
                id: "desc"
            },
            include: {
                Department: {
                    include: {
                        Science: {
                            include: {
                                Classes: true
                            }
                        }
                    }
                }
            }
        })
    }

    @Mutation(() => CollegeEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    async updCollege(
        @Args("id", { type: () => Int }) id: number,
        @Args("name") name: string
    ) {
        const find = await this.prisma.college.findUnique({ where: { name } })
        if (!!find && find.id !== id) {
            throw new ForbiddenError("名称已存在")
        }
        return await this.prisma.college.update({
            where: {
                id
            },
            data: {
                name
            }
        })
    }


    @Mutation(() => CollegeEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    async addCollege(
        @Args("name") name: string
    ) {
        if (!!await this.prisma.college.findUnique({ where: { name } })) throw new ForbiddenError("名称已存在")
        return this.prisma.college.create({
            data: {
                name
            }
        })
    }

}
